<?php
require_once 'City.class.php';
class IpLocation
{
    const URL = 'http://api.hostip.info/get_html.php?ip=';


    public static function getCityForIp($ip)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, self::URL . $ip);
        $data = curl_exec($ch);
        curl_close($ch);
        preg_match('/City: (.*)/', $data, $matches);
        $city = City::findByName($matches[1]);
        return $city->getId();
    }

    private static function getMyIp()
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        elseif (isset($_SERVER['HTTP_VIA'])) {
            $ip = $_SERVER['HTTP_VIA'];
        }
        elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        else {
            $ip = NULL;
        }
        return $ip;
    }

    public static function getCityForMyIp()
    {
        return self::getCityForIp(self::getMyIp());
    }
}

?>
